import os
import random
from io import BytesIO

from PIL import Image, ImageDraw, ImageFont
from django.db import models
from django.conf import settings
from django.http import HttpResponse


class CommonModel(models.Model):
    """公共模块"""
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('修改时间', auto_now=True)

    class Meta:
        abstract = True


"""
    如何生成验证码
        1.准备素材-字体（ttf）,文字内容，颜色，干扰线
        2.画验证码-pip install Pillow,random
            (1) 第一次请求，cookie + session 对应关系生成
            (2) 第二次请求，携带了cookie，找到对应的session,请求带上验证码参数 与 session中的验证码进行比较
        3.io文件流-BytesIO
"""
class VerifyCode(object):
    """验证码类"""
    def __init__(self, dj_request):
        # 得到请求的验证码对象
        self.dj_request = dj_request
        # 验证码长度
        self.code_len = 4
        # 验证码图片尺寸
        self.img_width = 100
        self.img_height = 30

        # django中session的名称
        self.session_key = 'verify_code'

    def gen_code(self):
        """生成验证码"""
        # 1.使用随机数生成验证码字符串
        code = self._get_vcode()
        # 2.把验证码存在session
        self.dj_request.session[self.session_key] = code
        # 3.准备随机元素（背景颜色、验证码文字颜色、干扰线）
        font_color = ['black', 'brown', 'red', 'darkred', 'green', 'darkmagenta', 'cyan', 'darkblue', 'darkcyan']
        # RGB随机背景色
        bg_color = (random.randrange(230, 255), random.randrange(230, 255), random.randrange(230, 255))
        # 字体路径
        font_path = os.path.join(settings.BASE_DIR, 'static', 'fonts', 'timesbi.ttf')
        # 创建图片
        img = Image.new('RGB', (self.img_width, self.img_height), bg_color)
        draw = ImageDraw.Draw(img)

        # 随机条数，到底画几条(画干扰线)
        for i in range(random.randrange(1, int(self.code_len / 2) + 1)):
            # 线条的颜色
            line_color = random.choice(font_color)
            # 线条的位置
            point = (random.randrange(0, self.img_width * 0.2),
                     random.randrange(0, self.img_height),
                     random.randrange(self.img_width - self.img_width * 0.2, self.img_width),
                     random.randrange(0, self.img_height))
            # 线条的宽度
            width = random.randrange(1, 4)
            draw.line(point, fill=line_color, width=width)

        # 画验证码
        for index, char in enumerate(code): # 枚举
            code_color = random.choice(font_color)
            font_size = random.randrange(15, 25)
            font = ImageFont.truetype(font_path, font_size)
            point = (index * self.img_width / self.code_len,
                       random.randrange(0, self.img_height / 3))
            draw.text(point, char, font=font, fill=code_color)


        # 创建文件流
        buf = BytesIO()
        img.save(buf, 'gif')
        return HttpResponse(buf.getvalue(), 'image/gif')


    def _get_vcode(self):
        random_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
        code_list = random.sample(list(random_str), self.code_len)
        code = ''.join(code_list)
        return code
    def validate_code(self, code):
        """验证码验证是否正确"""
        # 1. 转变大小写
        code = str(code).lower()
        # 获取session中存储的验证码
        vcode = self.dj_request.session.get(self.session_key, '')
        # if vcode.lower() == code:
        #     return True
        # else:
        #     return False
        # 比较用户输入的验证码和存储的验证码是否正确
        return vcode.lower() == code
